﻿using KTD.Web.Common;
using KTD.Web.Models;
using KTD.Web.Models.Enum;
using KTD.Web.Models.VD;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using XXS.Common;
using XXS.Common.BaseDataAccessLayer;
using XXS.Common.Paginate;

namespace KTD.Web.BLL
{
    public class HouseManager
    {
        private readonly IBaseDAL<House> _HouseDal;
        private readonly IBaseDAL<Member> _Memberl;
        private readonly IBaseDAL<Area> _AreaDal;
        public HouseManager()
        {
            _HouseDal = new BaseDAL<House>(new DB());
            _AreaDal = new BaseDAL<Area>(new DB());
            _Memberl = new BaseDAL<Member>(new DB());
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="im"></param>
        /// <returns></returns>
        public virtual IPaginate<HouseListVD> GetListBy(HouseQD im)
        {
            var res = _HouseDal.FindList();
            if (im.Status!= null)
            {
                res = res.Where(n => n.status == im.Status);
            }
          
            if (im.LikeMemberId != null&&im.LikeMemberId!=0)
            {
                var member = _Memberl.Find(im.LikeMemberId);
                if (member != null && !string.IsNullOrEmpty(member.LikeHouseIds))
                {
                    var ids = member.LikeHouseIds.TrimEnd(',').Split(',').Select(n => Convert.ToInt32(n));
                    res = res.Where(n => ids.Contains(n.Id));
                }
                else
                {
                    res = res.Where(n => false);
                }
            }
            if (im.CityId != null)
            {
                res = res.Where(n => n.cityid == im.CityId);
            }
            if (!string.IsNullOrEmpty(im.Channel))
            {
                res = res.Where(n => n.channel == im.Channel);
            }
            if (!string.IsNullOrEmpty(im.Name))
            {
                res = res.Where(n => n.housename.Contains(im.Name)||n.title.Contains(im.Name));
            }
            if (im.HouseAreaId!=null)
            {
                res = res.Where(n => n.houseareaid == im.HouseAreaId);
            }
            if (!string.IsNullOrEmpty(im.Query))
            {
                res = res.Where(n => n.name.Contains(im.Query) || n.areaname.Contains(im.Query)||n.houseaddress.Contains(im.Query)
                || n.housename.Contains(im.Query) || n.companyname.Contains(im.Query) || n.title.Contains(im.Query));
            }
            if (!string.IsNullOrEmpty(im.Area)&&im.Area!="区域")
            {
                res = res.Where(n => n.areaname == im.Area);
            }
            if (!string.IsNullOrEmpty(im.HouseType)&&im.HouseType!="业态")
            {
                res = res.Where(n => n.housetype.Contains(im.HouseType) );
            }
            if (!string.IsNullOrEmpty(im.HousePrice) && im.HousePrice != "不限")
            {
                var price = im.HousePrice.Split('-');
                var min = Convert.ToInt32(price[0]);
                var max = Convert.ToInt32(price[1]);
                res = res.Where(n => n.houseprice >= min && n.houseprice <= max);
            }
            //if (!string.IsNullOrEmpty(im.HousePrice) && im.HousePrice != "总价" && im.HousePrice != "不限")
            //{
            //    var price = im.HousePrice.Replace("万","").Split('-');
            //    var min = Convert.ToInt32(price[0]);
            //    var max = Convert.ToInt32(price[1]);
            //    res = res.Where(n => (n.minZongjia >= min&&n.minZongjia<=max )|| (n.maxZongjia >=min &&n.maxZongjia <= max));
            //}
            if (!string.IsNullOrEmpty(im.LetWay))
            {
                res = res.Where(n => n.letway == im.LetWay);
            }
            if (im.Hot == true)
            {
                res = res.Where(n => n.hot > 0);
                return res.OrderByDescending(n => n.hot)
               .ToPaginate(im, n => new HouseListVD().MapFrom(n));
            }
            if (im.Order == "按创建时间")
            {
                return res.OrderByDescending(n =>n.CreateDateTime)
               .ToPaginate(im, n => new HouseListVD().MapFrom(n));
            }
            else if (im.Order == "按热度")
            {
                return res.OrderByDescending(n => n.hot).ThenByDescending(n => n.CreateDateTime)
             .ToPaginate(im, n => new HouseListVD().MapFrom(n));
            }
            if (im.IsLast)
            {
                return res.OrderByDescending(n => n.hot).ThenByDescending(n => n.CreateDateTime)
                .ToPaginate(im, n => new HouseListVD().MapFrom(n));
            }
            return res.OrderByDescending(n => n.click)
                .ToPaginate(im,n => new HouseListVD().MapFrom(n));
            
        }

        public LocationVD GetLocation(LocationD im)
        {
            var vd =new LocationVD();
            var client = new WebClient();
            client.Encoding = Encoding.UTF8;
            var str = client.DownloadString($"https://apis.map.qq.com/ws/geocoder/v1/?location={im.latitude},{im.longitude}&key=XXIBZ-VD3EX-6TL4Y-TBIQX-WULEO-L5BVX&get_poi=1");

            //var model = JsonConvert.DeserializeObject<SalerRes>(res);

            JObject data = JsonConvert.DeserializeObject<JObject>(str);

            vd.Address = data["result"]["address"].ToString();
            vd.AddressName = data["result"]["formatted_addresses"]["recommend"].ToString(); ;
            PositionModel position = DistanceHelper.FindNeighPosition(im.longitude, im.latitude, 2);
            var res = _HouseDal.FindList(n => n.status == Status.审核通过 && n.channel == "new");
            var count = res.Count(n=>n.lat>position.MinLat&&n.lat<position.MaxLat&&n.lng>position.MinLng&&n.lng<position.MaxLng);
            vd.HouseList = new List<string> { $"新盘({count})"};
            return vd;
        }

        public virtual IEnumerable<SelectListItem> GetSelect()
        {
            var res = _HouseDal.FindList(n=>n.status==Status.审核通过&&n.channel=="new");

            return res.Select(n => new SelectListItem { Text = n.housename,  Value = n.housename }).ToList();
        }
        public virtual IEnumerable<HouseCUD> GetAllListBy(HouseQD im)
        {
            var res = _HouseDal.FindList(n=>n.content != null || n.content != "");
            if (!string.IsNullOrEmpty(im.Channel))
            {
                res = res.Where(n => n.channel == im.Channel&&(n.content!=null||n.content!=""));
            }
          
            var list = res.ToList()
                .Select(n => new HouseCUD().MapFrom(n));
            return list;
        }



        public int WxCreate(HouseCUD im)
        {
            House model = new House();
            im.MapTo(model);
            model.housetype = string.Join(",", im.housetypeList);
            if (im.thumb_urls != null)
            {
                model.thumb_url = string.Join(",", im.thumb_urls);
            }
            if (im.thumb_1s != null)
            {
                model.thumb_1 = string.Join(",", im.thumb_1s);
            }
            if (im.thumb_2s != null)
            {
                model.thumb_2 = string.Join(",", im.thumb_2s);
            }
            if (im.thumb_3s != null)
            {
                model.thumb_3 = string.Join(",", im.thumb_3s);
            }
            
            
           
           
            if (im.thumb_url != null && im.thumb_urls.Count != 0)
            {
                model.thumb = im.thumb_urls[0];
            }
            var area = _AreaDal.Find(n => n.name == im.areaname);
            if (area != null) {
                model.houseareaid = area.Id;
                model.cityid = area.uniacid;
            }
            model = _HouseDal.Create(model);
            return model.Id;
        }

        public int Create(HouseCUD im)
        {
            if (_HouseDal.Count(n => n.uid == im.uid) != 0)
            {
                var old = _HouseDal.FindList(n => n.uid == im.uid).FirstOrDefault();

                if (old != null)
                {
                    old.click = im.click;
                    old.clickstr = im.clickstr;
                    _HouseDal.Update(old);
                }

                return 0;
            }
            House model = new House();
            im.MapTo(model);
            var area = _AreaDal.Find(n => n.name == im.areaname);
            if (area != null)
            {
                model.cityid = area.uniacid;
                if (model.houseareaid == 0)
                {
                    model.houseareaid = area.Id;
                }
            }
            model.memberId = 1;
            model.CreateDateTime = DateTime.Now;
            model = _HouseDal.Create(model);
            return model.Id;
        }

        public void Update(HouseCUD im)
        {
            House model = _HouseDal.Find(im.Id);
            var thumb = model.thumb;
            
            if (model == null)
            {
                throw new Exception("错误的ID");
            }
            im.MapTo(model);
            
            var area = _AreaDal.Find(n => n.name == im.areaname);
            if (area != null)
            {
                model.houseareaid = area.Id;
                model.cityid = area.uniacid;
            }
            if (string.IsNullOrEmpty(im.thumb)) {
                model.thumb = thumb;
            }

            
            _HouseDal.Update(model);
        }

        public void UpdateSale(HouseCUD im)
        {
            House model = _HouseDal.Find(im.Id);
            var thumb = model.thumb;
            if (model == null)
            {
                throw new Exception("错误的ID");
            }
            model.houseareaid = im.houseareaid;
            model.area = im.areaname;
            model.title = im.title;
            model.housetype = im.housetype;
            model.housetypename = im.housetype;
            model.name = im.name;
            model.tel = im.tel;
            model.payway = im.payway;
            if (string.IsNullOrEmpty(im.thumb))
            {
                model.thumb = thumb;
            }
            _HouseDal.Update(model);
        }

        public HouseCUD Find(int id)
        {
            House model = _HouseDal.Find(id);
            return new HouseCUD().MapFrom(model);
        }



        public HouseDetailVD FindDetail(int id,int? MemberId)
        {

            var house = new HouseDetailVD();
            House model = _HouseDal.Find(id);
            var housevd= new HouseCUD().MapFrom(model);
            housevd.content = HttpUtility.HtmlDecode(housevd.content);
            house.House = housevd;
            house.GwList = MF.SalerManager.GetListBy(new SalerQD { PageSize = 3, HouseId = model.Id,Type="gw",Status=Status.审核通过 }).PageData;
            house.SaleList = MF.SalerManager.GetListBy(new SalerQD { PageSize = 3, HouseId = model.Id, Type = "sale", Status = Status.审核通过 }).PageData;
            house.LikeList= MF.HouseManager.GetListBy(new HouseQD { PageSize = 3,Channel="new", HouseAreaId = model.houseareaid, Status = Status.审核通过 }).PageData;
            house.CommentList= MF.CommentManager.GetListBy(new CommentQD { PageSize = 3, HouseId = model.Id }).PageData;
            if (MemberId != null&&MemberId!=0)
            {
                var member = _Memberl.Find(MemberId);
               
                if (member!=null&&member.LikeHouseIds!=null&&member.LikeHouseIds.Split(',').Contains(housevd.Id.ToString()))
                {
                    house.IsLike = true;
                }
                else
                {
                    house.IsLike = false;
                }
            }
            model.click++;
            _HouseDal.Update(model);
            return house;
        }

        public void Delete(int id)
        {
            House model = _HouseDal.Find(id);
            if (model == null)
            {
                throw new Exception("错误的ID");
            }
            _HouseDal.Delete(model);
        }

        public IEnumerable<HouseMapVD> GetHosueMapList(HouseMapQD im)
        
        {
            if (im.HouseAreaId == null&&string.IsNullOrEmpty(im.Area)&&im.Latitude==null && im.Longitude == null)
            {
                var AreaList = _AreaDal.FindList().ToList();
              //  var list = _HouseDal.FindList().GroupBy(n => n.houseareaid).ToList();
                var houseList = new List<HouseMapVD>();
                foreach (var item in AreaList)
                {
                    
                  
                    if (item != null) {
                        //item.Title = area.name+"("+item.Count+")";
                        //item.Lng = area.lng;
                        //item.Lat = area.lat;
                        //item.Type = "区域";
                        var res= _HouseDal.FindList(n=>n.houseareaid == item.Id);


                        if (!string.IsNullOrEmpty(im.Query))
                         {
                            res = res.Where(n => n.name.Contains(im.Query) || n.areaname.Contains(im.Query) || n.houseaddress.Contains(im.Query)
                            || n.housename.Contains(im.Query) || n.companyname.Contains(im.Query) || n.title.Contains(im.Query));
                        }

                        if (!string.IsNullOrEmpty(im.HouseType)&&im.HouseType != "业态" && im.HousePrice != "业态")
                        {
                            res = res.Where(n => n.housetype.Contains(im.HouseType));
                        }
                        if (!string.IsNullOrEmpty(im.HousePrice) && im.HousePrice != "不限")
                        {
                            var price = im.HousePrice.Split('-');
                            var min = Convert.ToInt32(price[0]);
                            var max = Convert.ToInt32(price[1]);
                            res = res.Where(n => n.houseprice >= min && n.houseprice <= max);
                        }
                        //if (!string.IsNullOrEmpty(im.HousePrice)&&im.HousePrice!="总价" && im.HousePrice != "不限")
                        //{
                        //    var price = im.HousePrice.Replace("万", "").Split('-');
                        //    var min = Convert.ToInt32(price[0]);
                        //    var max = Convert.ToInt32(price[1]);
                        //    res = res.Where(n => (n.minZongjia >= min && n.minZongjia <= max) || (n.maxZongjia >= min && n.maxZongjia <= max));
                        //}
                        var  count = res.Count();

                        houseList.Add(new HouseMapVD(item.Id, item.name + "(" + count + ")", item.lng, item.lat));
                    }
                }
                return houseList;
            }
            else
            {
                using (var db = new DB())
                {
                    var res = db.Houses.Where(n=>n.status==Status.审核通过&&n.channel=="new");
                    //var res = _HouseDal.FindList();
                    if (im.HouseAreaId != null)
                    {
                        res = res.Where(n => n.houseareaid == im.HouseAreaId);
                    }
                    if (!string.IsNullOrEmpty(im.Area))
                    {
                        res = res.Where(n => n.areaname == im.Area);
                    }
                    if (!string.IsNullOrEmpty(im.Query))
                    {
                        res = res.Where(n => n.name.Contains(im.Query) || n.areaname.Contains(im.Query) || n.houseaddress.Contains(im.Query)
                        || n.housename.Contains(im.Query) || n.companyname.Contains(im.Query) || n.title.Contains(im.Query));
                    }

                    if (!string.IsNullOrEmpty(im.HouseType))
                    {
                        res = res.Where(n => n.housetype.Contains(im.HouseType));
                    }
                    //if (!string.IsNullOrEmpty(im.HousePrice))
                    //{
                    //    var price = im.HousePrice.Split('-');
                    //    var min = Convert.ToInt32(price[0]);
                    //    var max = Convert.ToInt32(price[1]);
                    //    res = res.Where(n => n.houseprice >= min && n.houseprice <= max);
                    //}
                    if (!string.IsNullOrEmpty(im.HousePrice))
                    {
                        var price = im.HousePrice.Replace("万", "").Split('-');
                        var min = Convert.ToInt32(price[0]);
                        var max = Convert.ToInt32(price[1]);
                        res = res.Where(n => (n.minZongjia >= min && n.minZongjia <= max) || (n.maxZongjia >= min && n.maxZongjia <= max));
                    }
                    if (im.Longitude != null && im.Latitude != null)
                    {
                        PositionModel position = DistanceHelper.FindNeighPosition(im.Longitude.Value, im.Latitude.Value, im.Distance);
                        res = res.Where(n => n.lat > position.MinLat && n.lat < position.MaxLat && n.lng > position.MinLng && n.lng < position.MaxLng);
                    }

                    return res.ToList().Select(n => new HouseMapVD(n.Id, n.housename+"("+n.housetype+")", n.lng, n.lat));

                }
            }
           
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="im"></param>
        /// <returns></returns>
        public virtual IPaginate<HouseListVD> GetLikeHouses(LikeQD im)
        {
            var member = _Memberl.Find(im.MemberId);
            var res = _HouseDal.FindList(n=> n.status==Status.审核通过&&member.LikeHouseIds.Contains(n.Id.ToString()));
           
            
            return res.OrderByDescending(n => n.click)
                .ToPaginate(im, n => new HouseListVD().MapFrom(n));

        }


        public List<string> FindNameListBy(HouseQD im)
        {
            im.Status = Status.审核通过;
            var list = GetListBy(im).PageData.Select(n=>string.IsNullOrEmpty(n.housename)?n.title:n.housename).ToList();

            return list;

        }
    }
}